const { db, query } = require("../database/db")
// 添加角色
const createrole = (name, description, createtime, rolecode) => {
    let sql = `INSERT INTO roles (name,description,createtime,rolecode) VALUES (?,?,?,?)`
    return query(sql, [name, description, createtime, rolecode])
}
// 删除角色--软删除
const delete_f = (id) => {
    let sql = `UPDATE roles SET state = 1 WHERE id = ?`
    return query(sql, id)
}

// 删除角色--软删除
const start_status = (id) => {
    let sql = `UPDATE roles SET state = 0 WHERE id = ?`
    return query(sql, id)
}

// 删除角色---真删除
const delete_t = (id) => {
    let sql = `DELETE FROM roles WHERE id = ?`
    return query(sql, id)
}
// 角色的列表搜索列表--分页
const role_list = async (name, rolecode, page_size, page) => {
    let listSql = `SELECT * FROM roles`;
    let params = [];


    let conditions = [`0 = 0`];

    if (name) {
        conditions.push(`name LIKE ?`);
        params.push(`%${name}%`);
    }
    if (rolecode) {
        conditions.push(`rolecode LIKE ?`);
        params.push(`%${rolecode}%`);
    }

    if (conditions.length > 0) {
        listSql += ` WHERE ${conditions.join(' AND ')}`;
    }

    // 添加分页的SQL语句
    listSql += ` LIMIT ? OFFSET ?`;

    // 添加分页参数
    params.push(page_size);
    params.push((page - 1) * page_size);

    let countSql = `SELECT COUNT(*) as count FROM roles WHERE ${conditions.map(c => `(${c})`).join(' AND ')}`;

    try {
        const [rolesResult, countResult] = await Promise.all([
            query(listSql, params), // 查询角色列表
            query(countSql, params) // 查询总数
        ]);
        return {
            roles: rolesResult, // 角色列表
            total: countResult // 总数
        };
    } catch (error) {
        console.error('查询失败:', error);
        throw error; // 重新抛出错误，或者根据需要进行错误处理
    }
};
// 角色的修改--get数据
const edit_get = (id) => {
    let sql = `SELECT id,name,description,createtime,updatetime,rolecode FROM roles WHERE id = ? AND state = 0`
    return query(sql, [id])
}
// 角色的修改--set数据
const edit_set = (id, name, description, updatetime, rolecode) => {
    let sql = `UPDATE roles SET name = ?, description = ?, updatetime = ?, rolecode = ? WHERE id= ?`
    // 传数据的时候，注意数组的顺序，一一对应
    return query(sql, [name, description, updatetime, rolecode, id])
}
// 角色的权限设置操作
const expression_set = (id, permission_ids) => {
    let sql = `
    UPDATE roles 
    SET permission_ids = ? 
    WHERE 
    id = ?`;
    return query(sql, [permission_ids, id]); // 确保参数顺序与SQL语句中的占位符顺序一致
}
// 角色的权限查看详情
const expression_view = async (id) => {
    // 参数验证
    if (!id || isNaN(Number(id))) {
        throw new Error('INVALID_INPUT: 角色ID必须为有效数字');
    }

    try {
        // 1. 查询角色基础信息
        const roleSql = `
            SELECT id, name as role_name, permission_ids 
            FROM roles 
            WHERE id = ? AND state = 0
        `;
        const [roleResults] = await query(roleSql, [id]);

        if (!roleResults || roleResults.length === 0) {
            throw new Error('NOT_FOUND: 未找到该角色或角色已被删除');
        }

        const role = roleResults;
        console.log("角色：：：",role.permission_ids.split(','))
        let permissionIds = [];

        try {
            permissionIds = role.permission_ids.split(',') || [];
            console.log("我需要的权限格式：：",permissionIds)
            if (!Array.isArray(permissionIds)) {
                throw new Error('DATA_FORMAT_ERROR');
            }
        } catch (e) {
            throw new Error('DATA_FORMAT_ERROR: 权限ID格式不正确');
        }

        // 2. 如果没有权限，直接返回空结构
        if (permissionIds.length === 0) {
            return {
                roleId: role.id,
                roleName: role.role_name,
                permissions: {
                    level0: [],
                    level1: [],
                    level2: [],
                    level3: []
                },
                total: 0,
                msg: '该角色未分配任何权限'
            };
        }

        // 3. 查询权限详细信息
        const permissionSql = `
            SELECT 
                id, 
                name, 
                type, 
                component_url as component,
                icon
            FROM permission
            WHERE id IN (?)
            ORDER BY type ASC
        `;
        const permissionResults = await query(permissionSql, [permissionIds]);
        console.log("结果：：：：",permissionResults)
        // 4. 按权限等级分类 (type: 1=菜单, 2=页面, 3=操作)
        const categorized = permissionResults.reduce((acc, permission) => {
            const level = `level${permission.type}`;
            if (!acc[level]) {
                acc[level] = [];
            }

            acc[level].push({
                id: permission.id,
                name: permission.name,
                component: permission.component || '',
                icon: permission.icon || ''
            });

            return acc;
        }, {});

        // 5. 确保所有级别都存在
        const finalPermissions = {
            level0: categorized.level0 || [],
            level1: categorized.level1 || [],
            level2: categorized.level2 || [],
            level3: categorized.level3 || []
        };

        // 6. 返回结构化数据
        return {
            roleId: role.id,
            roleName: role.role_name,
            permissions: finalPermissions,
            total: permissionResults.length,
            updatedAt: new Date().toISOString()
        };

    } catch (error) {
        console.error(`[RolePermissionModel] 查询角色权限失败: ${error.message}`);
        throw new Error(`QUERY_FAILED: ${error.message}`);
    }
};
// 角色的列表-下拉菜单
const all_role = () => {
    let sql = `
        SELECT id, name, rolecode FROM roles ORDER BY id ASC;
    `
    return query(sql)
}

module.exports = {
    createrole,
    delete_f,
    start_status,
    delete_t,
    role_list,
    edit_get,
    edit_set,
    expression_set,
    all_role,
    expression_view
}